import { getUserInfoService, userLoginService } from '@/api/user'
import { createSlice } from '@reduxjs/toolkit'
import { tokenOperator } from '@/utils'
const userStore = createSlice({
  name: 'user',
  initialState: {
    token: tokenOperator.getToken() || '',
    userInfo: {}
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      tokenOperator.setToken(action.payload)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo(state) {
      console.log('clearUserInfo')
      state.token = ''
      state.userInfo = {}
      tokenOperator.removeToken()
    }
  }
})

const { setToken, setUserInfo, clearUserInfo } = userStore.actions

const fetchToken = (loginForm) => async (dispatch) => {
  const res = await userLoginService(loginForm)
  dispatch(setToken(res.data.token))
}

const fetchUserInfo = () => async (dispatch) => {
  const res = await getUserInfoService()
  dispatch(setUserInfo(res.data))
}

export { fetchToken, fetchUserInfo, clearUserInfo }
export default userStore.reducer
